import 'package:enjoy_plus_bryant/utils/eventbus.dart';
import 'package:enjoy_plus_bryant/utils/http.dart';
import 'package:enjoy_plus_bryant/utils/toast.dart';
import 'package:enjoy_plus_bryant/utils/token.dart';
import 'package:flutter/material.dart';

class MinePage extends StatefulWidget {
  MinePage({super.key, this.currentIndex});
  // 接收传递的index
  int? currentIndex;
  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 菜单数据
  final List menuList = [
    {"title": "我的房屋", "icon": "assets/images/house_profile_icon@2x.png"},
    {"title": "我的报修", "icon": "assets/images/repair_profile_icon@2x.png"},
    {"title": "访客记录", "icon": "assets/images/visitor_profile_icon@2x.png"},
  ];

  // --------------------- 获取用户信息
  // 1. 定义对象接收接口数据
  Map profile = {'id': '', 'avatar': null, 'nickName': null};
  // 2. 调用接口获取数据
  void getProfile() async {
    try {
      var res = await http.get('/userInfo');
      if (res['code'] != 10000) {
        return ToastUtil.showError('获取用户信息失败');
      }
      // print(res);
      setState(() {
        profile = res['data'];
      });
    } catch (e) {
      print(e);
    }
  }

  /// 退出登录
  logoutTap() async {
    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('提示'),
          content: const Text('确定要退出登录吗？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                setState(() {
                  profile = {'id': '', 'avatar': null, 'nickName': null};
                });
                TokenManager().removeToken();
                Navigator.pop(context);
                eventBus.fire(LogoutRefresh());
                // Navigator.pushReplacementNamed(context, '/login');
              },
              child: const Text('确定', style: TextStyle(color: Colors.grey)),
            ),
          ],
        );
      },
    );
  }

  // 监听tabbar组件传递的index， 使用didUpdateWidget生命周期进行监听 - 在构建widget时，会调用一次didUpdateWidget
  @override
  didUpdateWidget(oldWidget) {
    super.didUpdateWidget(oldWidget);
    // print(widget.currentIndex);
    if (widget.currentIndex == 1) {
      // 调用接口获取用户信息
      getProfile();
    }
  }

  @override
  void initState() {
    super.initState();
    // 1. 监听刷新用户信息事件 - 登录后执行
    eventBus.on<RefreshUserInfoEvent>().listen((event) {
      getProfile();
    });

    // 2. 监听修改呢称事件， 修改呢称完成后执行
    eventBus.on<RefreshNickname>().listen((event) {
      setState(() {
        profile['nickName'] = event.nickname;
        profile['avatar'] = event.avatar;
      });
    });

    // 3. 监听退出登录
    eventBus.on<LogoutRefresh>().listen((event) {
      getProfile();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text('我的', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                // 点击跳转个人信息修改也，但main中需要鉴权
                Navigator.pushNamed(context, '/profile', arguments: profile);
              },
              child: Row(
                children: [
                  Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(50.0),
                        child: profile['avatar'] == null
                            ? Image.asset(
                                'assets/images/avatar_1.jpg',
                                width: 50,
                                height: 50,
                              )
                            : Image.network(
                                profile['avatar'],
                                width: 50,
                                height: 50,
                              ),
                      ),
                      const SizedBox(width: 10),
                      Text(
                        profile['nickName'] ?? '用户名',
                        style: const TextStyle(
                          fontSize: 16,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                  const Spacer(),
                  const Row(
                    children: [
                      Text('去完善信息', style: TextStyle(color: Colors.white)),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.white,
                        size: 13,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            margin: const EdgeInsets.only(
              top: 20,
              left: 10,
              right: 10,
              bottom: 20,
            ),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: menuList.map((item) {
                return SizedBox(
                  height: 50,
                  child: GestureDetector(
                    onTap: () {
                      // 点击跳转
                      if (item['title'] == '我的房屋') {
                        Navigator.pushNamed(context, '/house_list');
                      }
                    },

                    child: Row(
                      children: [
                        Row(
                          children: [
                            Image.asset(item['icon'], width: 20, height: 20),
                            const SizedBox(width: 10),
                            Text(
                              item['title'],
                              style: const TextStyle(fontSize: 16),
                            ),
                          ],
                        ),
                        const Spacer(),
                        const Icon(
                          Icons.arrow_forward_ios,
                          size: 12,
                          color: Colors.grey,
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
            ),
          ),

          ElevatedButton(
            onPressed: () {
              logoutTap();
            },
            child: Text('退出登录'),
          ),
        ],
      ),
    );
  }
}
